<template>
  <Form
    class="xtx-form"
    ref="formCom"
    v-slot="{ errors }"
    :validation-schema="schema"
  >
    <h3>{{ errors }}</h3>
    <div class="user-info">
      <img :src="avatar" alt="" />
      <p>Hi，{{ nickname }} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          v-model="form.mobile"
          name="mobile"
          :class="{ error: errors.mobile }"
          class="input"
          type="text"
          placeholder="绑定的手机号"
        />
      </div>
      <div class="error" v-if="errors.mobile">{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          v-model="form.code"
          name="code"
          :class="{ error: errors.code }"
          class="input"
          type="text"
          placeholder="短信验证码"
        />
        <span class="code" @click="sendCodeBtn">
          {{ number === 0 ? "发送验证码" : `${number}秒后发送` }}
        </span>
      </div>
      <div class="error" v-if="errors.code">{{ errors.code }}</div>
    </div>
    <a href="javascript:;" @click="loginBtn" class="submit">立即绑定</a>
  </Form>
</template>

<script>
import { reactive, ref, watch } from 'vue'
import schema from '@/utils/vee-validate-schema'
import { Form, Field } from 'vee-validate'
import Message from '@/components/library/Message'
import { useIntervalFn } from '@vueuse/shared'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

export default {
  name: 'CallbackBind',
  components: { Form, Field },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    const nickname = ref('')
    const avatar = ref('')
    // 业务1：获取QQ用户公开信息
    if (QC.Login.check()) {
      QC.api('get_user_info').success(({ data }) => {
        // console.log(res)
        nickname.value = data.nickname
        avatar.value = data.figureurl_2
      })
    }

    // 业务2：获取表单数据和表单校验
    const formCom = ref(null)
    const form = reactive({
      unionId: '',
      mobile: '',
      code: ''
    })

    watch(
      () => props.unionId,
      unionId => {
        form.unionId = unionId
      },
      { immediate: true }
    )

    // 业务3：发送验证码
    const number = ref(0)
    const { resume, pause } = useIntervalFn(
      () => {
        number.value--
        if (number.value <= 0) {
          pause()
        }
      },
      1000,
      { immediate: false }
    )

    const sendCodeBtn = async () => {
      // 校验手机号码 form.mobile
      const mobileChecked = schema.mobile(form.mobile)
      // console.log(res)
      if (mobileChecked === true) {
        // 🔔上一个倒计时没有结束，直接退出
        if (number.value !== 0) return
        // 发送验证码
        try {
          // 💥
          await userQQBindCode(form.mobile)
          Message({ type: 'success', message: '验证码发送成功' })
          // 倒计时秒数重置
          number.value = 60
          // 调用倒计时
          resume()
        } catch (err) {
          Message({ type: 'error', message: err.response.data.message || '获取验证码出现错误' })
        }
      } else {
        formCom.value.setFieldError('mobile', mobileChecked)
      }
    }

    // 业务4：登录请求发送
    const store = useStore()
    const router = useRouter()
    // 登录提交
    const loginBtn = async () => {
      // 主动获取表单校验结果
      const valid = await formCom.value.validate()
      if (!valid) return Message({ type: 'error', message: '表单校验失败' })
      // console.log('表单校验是否通过', valid)
      // 测试账号：sujiehao   密码：123456
      try {
        const { result } = await userQQBindLogin(form)
        // console.log(result)
        // // console.log(result)
        // 1. 存储 token 信息
        store.commit('user/setUser', result)
        // 2. 页面跳转（两种情况：1.回跳到某个页面 2.跳转首页）
        // router.currentRoute.value 获取当前路由
        const redirectUrl = router.currentRoute.value.query.redirectUrl
        router.push(redirectUrl || '/')
        // 成功提示
        Message({ type: 'success', message: 'QQ登录成功' })
        // 登录成功后合并购物车数据
        store.dispatch('cart/mergeLocalCart')
      } catch (err) {
        // alert(err.response.data.message)
        // 失败提示
        Message({ type: 'error', message: err.response.data.message })
      }
    }

    return { nickname, avatar, form, schema, formCom, sendCodeBtn, number, loginBtn }
  }
}
</script>

<style scoped lang="less">
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
